const mongoose = require('mongoose');
const User = mongoose.model('User');
const OrderForm = mongoose.model('OrderForm');
const DisOrderForm = mongoose.model('DisOrderForm');

const orderFormTypeList = ['中通', '圆通', '申通', '顺丰', '百世', '韵达', '天天', '京东', '近邻宝1', '近邻宝2', '近邻宝3', '其它'];

// 格式化输出日期
Date.prototype.Format = function(fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

// 是否登录的状态变量
let username = "";
let login = false;
let userPower = false;

// 检测 session 检测是否登录
const checkSession = (ctx) => {
    try {
        if (ctx.session.login === "1") {
            //已登录
            // let user = User.findOne({username: ctx.session.username});
            // return {
            //     login: true,
            //     loginUser: user
            // }
            login = true;
            username = ctx.session.username;
            userPower = (req.session.userType === "admin" || req.session.userType === "boss");
        } else {
            //未登录
            // return {
            //     login: false
            // };
            login = false;
            username = "";
            userPower = false;
        }
    } catch (err) {
        console.log(err);
    }
};


let showIndex = async (ctx, next) => {
    try {

        await checkSession(ctx);

        // if (ctx.session.login === "1") {
        //     //已登录
        //     var login = true;
        //     var username = ctx.session.username;
        // } else {
        //     //未登录
        //     var username = "";
        //     var login = false;
        // }

        if (login) {

            // console.time("串并行");
            // 串行操作，效率低
            let loginUser = await User.findOne({ username: username });
            let count_allOrderForm = await OrderForm.find({});
            let count_myOrderForm = await OrderForm.find({ username: username });
            let count_undoneOrderForm = await OrderForm.find({ of_status: "待取件" });

            // 并行操作，效率高
            // let loginUser_promise = User.findOne({ username: username });
            // let count_allOrderForm_promise = OrderForm.find({});
            // let count_myOrderForm_promise = OrderForm.find({ username: username });
            // let count_undoneOrderForm_promise = OrderForm.find({ of_status: "待取件" });
            // let loginUser = await loginUser_promise;
            // let count_allOrderForm = await count_allOrderForm_promise;
            // let count_myOrderForm = await count_myOrderForm_promise;
            // let count_undoneOrderForm = await count_undoneOrderForm_promise;

            await ctx.render('index', {
                login: login,
                loginUser: loginUser,
                count_allOrderForm: count_allOrderForm.length,
                count_myOrderForm: count_myOrderForm.length,
                count_undoneOrderForm: count_undoneOrderForm.length
            });

            // console.timeEnd("串并行");
        } else {
            await ctx.render('index', {
                login: login
            });
        }
    } catch (err) {
        console.log(err);
        ctx.response.body = err;
    }
};

let doLogin = async (ctx, next) => {
    try {
        // let login_sta = await checkSession(ctx);  // login 是一个对象


        let username = ctx.request.body.username;

        let result = await User.findOne({username: username});

        if (!result) {
            let newUser = {
                "username": username,
                "joinTimestamp": parseInt(new Date().getTime() / 1000) // 创建时的时间戳，除 1000 将单位从毫秒变为秒
            };

            User.create(newUser);
            console.log("注册并登录用户" + username + "成功" + new Date().Format("yyyy-MM-dd hh:mm:ss"));
            ctx.session.login = "1";
            ctx.session.username = username;
            ctx.session.userType = "common";
            ctx.response.body = 2;
        }
        if (result) {
            console.log("登录用户" + username + "成功" + new Date().Format("yyyy-MM-dd hh:mm:ss"));
            ctx.session.login = "1";
            ctx.session.username = username;
            ctx.session.userType = result.userType;
            ctx.response.body = 1;
        }
    } catch (err) {
        console.log(err);
        ctx.response.body = err;
    }
};

let doLogout = async (ctx, next) => {
    try {
        await checkSession(ctx);

        if (login) {

            console.log("注销用户" + username + "成功" + new Date().Format("yyyy-MM-dd hh:mm:ss"));
            ctx.session.login = "0";
            ctx.session.username = "";
            ctx.session.userType = "common";
            ctx.redirect("/")
        } else {
            await ctx.render('index', {
                login: login
            });
        }
    } catch (err) {
        console.log(err);
        ctx.response.body = err;
    }
};



let showNewOrderForm = async (ctx, next) => {
    try {
        await checkSession(ctx);

        if (login) {
            let result = await User.findOne({username: username});


            await ctx.render('newOrderForm', {
                login: login,
                loginUser: result
            });
        } else {
            await ctx.render('index', {
                login: login
            });
        }
    } catch (err) {
        console.log(err);
        ctx.response.body = err;
    }
};


let doNewOrderForm = async (ctx, next) => {
    try {
        await checkSession(ctx);

        if (login) {
            let newOrderForm = ctx.request.body;
            newOrderForm.username = username;
            newOrderForm.joinTimestamp = parseInt(new Date().getTime() / 1000) // 创建时的时间戳，除 1000 将单位从毫秒变为秒

            let newUserInfo = {
                "of_name": newOrderForm.of_name,
                "of_phone": newOrderForm.of_phone,
                "of_address": newOrderForm.of_address,
                "of_tailNumber": newOrderForm.of_tailNumber
            };


            await User.update({username: username}, newUserInfo);
            console.log(username + "更新用户信息成功" + new Date().Format("yyyy-MM-dd hh:mm:ss"));
            await OrderForm.create(newOrderForm);
            console.log(username + "创建新订单成功" + new Date().Format("yyyy-MM-dd hh:mm:ss"));
            ctx.response.body = 1;
        } else {
            await ctx.render('index', {
                login: login
            });
        }
    } catch (err) {
        console.log(err);
        ctx.response.body = err;
    }
};



let getOrderFormTypeList = async (ctx, next) => {
    try {
        await checkSession(ctx);


        if (login) {
            ctx.response.body = orderFormTypeList;
        } else {
            await ctx.render('index', {
                login: login
            });
        }
    } catch (err) {
        console.log(err);
        ctx.response.body = err;
    }
};


let getDiscardOrderFormList = async (ctx, next) => {
    try {
        await checkSession(ctx);


        if (login) {

            let findObj = JSON.parse(ctx.request.body.findObj);
            let result = await DisOrderForm.find(findObj);

            ctx.response.body = result.reverse();
        } else {
            await ctx.render('index', {
                login: login
            });
        }
    } catch (err) {
        console.log(err);
        ctx.response.body = err;
    }
};

let getOrderFormList = async (ctx, next) => {
    try {
        await checkSession(ctx);


        if (login) {
            let findObj = JSON.parse(ctx.request.body.findObj);
            let result = await OrderForm.find(findObj);

            ctx.response.body = result.reverse();
        } else {
            await ctx.render('index', {
                login: login
            });
        }
    } catch (err) {
        console.log(err);
        ctx.response.body = err;
    }
};

let getUserList = async (ctx, next) => {
    try {
        await checkSession(ctx);


        if (login) {
            let findObj = JSON.parse(ctx.request.body.findObj);
            let result = await User.find(findObj);

            ctx.response.body = result.reverse();
        } else {
            await ctx.render('index', {
                login: login
            });
        }
    } catch (err) {
        console.log(err);
        ctx.response.body = err;
    }
};

let showDiscardOrderForm = async (ctx, next) => {
    try {
        await checkSession(ctx);

        if (login) {
            let result = await User.findOne({username: username});
            if (userPower) {
                await ctx.render('orderFormList', {
                    login: login,
                    loginUser: result,
                    orderFormTypeList: orderFormTypeList,
                    title: "废弃订单",
                    mark: "discardOrderForm",
                    findObj: "",
                    findUrl: "/getDiscardOrderFormList"
                });
            } else {
                await ctx.render('index', {
                    login: login,
                    loginUser: result
                });
            }
        } else {
            await ctx.render('index', {
                login: login
            });
        }
    } catch (err) {
        console.log(err);
        ctx.response.body = err;
    }
};

let showUndoneOrderForm = async (ctx, next) => {
    try {
        await checkSession(ctx);

        if (login && userPower) {

            let result = await User.findOne({username: username});
            await ctx.render('orderFormList', {
                login: login,
                loginUser: result,
                orderFormTypeList: orderFormTypeList,
                title: "未完成订单",
                mark: "undoneOrderForm",
                findObj: {
                    key: "of_status",
                    value: "待取件"
                },
                findUrl: "/getOrderFormList"
            });
        } else {
            await ctx.render('index', {
                login: login
            });
        }
    } catch (err) {
        console.log(err);
        ctx.response.body = err;
    }
};
// let post = async (ctx, next) => {
//     await ctx.render('index3', {
//         name: "zty3"
//     });
// };
//
// let login = async (ctx, next) => {
//     let name = ctx.request.body.name;
//     ctx.response.body = `name:${name}`
// };

module.exports = {
    'GET /': showIndex,
    'POST /doLogin': doLogin,
    'GET /doLogout': doLogout,

    'GET /newOrderForm': showNewOrderForm,
    'POST /doNewOrderForm': doNewOrderForm,

    'GET /discardOrderForm': showDiscardOrderForm,
    'GET /undoneOrderForm': showUndoneOrderForm,
    'GET /myOrderForm': showMyOrderForm,
    'GET /allOrderForm': showAllOrderForm,
    'GET /adminManage': showAdminManage,


    'POST /getOrderFormTypeList': getOrderFormTypeList,
    'POST /getDiscardOrderFormList': getDiscardOrderFormList,
    'POST /getOrderFormList': getOrderFormList,
    'POST /getUserList': getUserList,
};


